package com.pyb.java.network.observers;

import android.text.TextUtils;

import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.exception.ResponseCodeUtils;
import com.pyb.java.network.exception.RxExceptionUtil;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public abstract class ResponseObserve<T> implements Observer<ResponseEntity<T>> {

    public abstract void onSuccess(ResponseEntity<T> responseEntity);

    public void onFail(String errorMsg){};

    public abstract void onSubscribeStart(@NonNull Disposable disposable);

    public void onFinish(){};

    /**
     * 返回正确数据
     *
     * @param response
     */
    @Override
    public void onNext(ResponseEntity<T> response) {
        try {
            if (response.getStatus() == 1) {
                onSuccess(response);
            } else {
//                String codeReturnMsg = ResponseCodeUtils.codeReturnMsg(response.getStatus());
//                if (TextUtils.isEmpty(codeReturnMsg)) {
//                    onFail(TextUtils.isEmpty(response.getMsg()) ? "请求异常，请查找问题" : response.getMsg());
//                } else {
//                    onFail(codeReturnMsg);
//                }
                onFail(response.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            onFinish();
        }
    }

    /**
     * 返回错误
     *
     * @param throwable
     */
    @Override
    public void onError(Throwable throwable) {
        try {
            String errorMsg = "";
            errorMsg = RxExceptionUtil.exceptionHandler(throwable);
            onFail(errorMsg);
            onComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onComplete() {
        onFinish();
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        onSubscribeStart(d);
    }
}
